<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <h2>用户注册</h2>
        <p>在线商城购物系统</p>
      </div>
      
      <div class="register-form">
        <el-form :model="registerForm" :rules="rules" ref="registerFormRef" size="large" label-position="top">
          <div class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :headers="uploadHeaders"
            >
              <img v-if="registerForm.avatar" :src="baseUrl + registerForm.avatar" class="avatar-preview" />
              <el-icon v-else class="avatar-icon"><Plus /></el-icon>
              <div class="avatar-text">点击上传头像</div>
            </el-upload>
          </div>
          
          <div class="form-row">
            <el-form-item label="用户名" prop="username" class="form-item">
              <el-input 
                v-model="registerForm.username" 
                placeholder="请输入用户名" 
              >
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="昵称" prop="nickname" class="form-item">
              <el-input 
                v-model="registerForm.nickname" 
                placeholder="请输入昵称" 
              >
                <template #prefix>
                  <el-icon><UserFilled /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="密码" prop="password" class="form-item">
              <el-input 
                v-model="registerForm.password" 
                type="password" 
                placeholder="请输入密码" 
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="确认密码" prop="confirmPassword" class="form-item">
              <el-input 
                v-model="registerForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入密码" 
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="手机号码" prop="phone" class="form-item">
              <el-input 
                v-model="registerForm.phone" 
                placeholder="请输入手机号码" 
              >
                <template #prefix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="电子邮箱" prop="email" class="form-item">
              <el-input 
                v-model="registerForm.email" 
                placeholder="请输入电子邮箱" 
              >
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </div>
          
          <el-form-item label="收货地址" prop="address">
            <el-input 
              v-model="registerForm.address" 
              type="textarea"
              rows="3"
              placeholder="请输入详细收货地址" 
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" class="register-button" @click="handleRegister(registerFormRef)" :loading="isSubmitting" :disabled="isSubmitting">
              {{ isSubmitting ? '注册中...' : '立即注册' }}
            </el-button>
          </el-form-item>
          
          <div class="login-link">
            <span>已有账号?</span>
            <router-link to="/login">返回登录</router-link>
          </div>
        </el-form>
      </div>
      
      <div class="register-footer">
        <p>Copyright © 2023 在线商城 All Rights Reserved.</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserWebRegister'
}
</script>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { User, Lock, UserFilled, Iphone, Message, Plus } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { inject } from 'vue';
import md5 from 'js-md5';

const router = useRouter();
const $axios = inject('$axios');
const registerFormRef = ref(null);
const uploadUrl = 'http://localhost:9191/file/upload'; // 头像上传地址
const baseUrl = 'http://localhost:9191'; // 后端服务器基础地址
const uploadHeaders = {}; // 根据需要设置上传头信息
const isSubmitting = ref(false); // 表单提交状态

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  phone: '',
  email: '',
  address: '',
  avatar: ''
});

// 验证密码是否一致
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'));
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'));
  } else {
    callback();
  }
};

// 验证手机号格式
const validatePhone = (rule, value, callback) => {
  if (value && !/^1[3456789]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号码'));
  } else {
    callback();
  }
};

// 验证邮箱格式
const validateEmail = (rule, value, callback) => {
  if (value && !/^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(value)) {
    callback(new Error('请输入正确的电子邮箱'));
  } else {
    callback();
  }
};

// 表单验证规则
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应在3-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass, trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度应在2-20个字符之间', trigger: 'blur' }
  ],
  phone: [
    { validator: validatePhone, trigger: 'blur' }
  ],
  email: [
    { validator: validateEmail, trigger: 'blur' }
  ],
  address: [
    { max: 200, message: '地址长度不能超过200个字符', trigger: 'blur' }
  ]
});

// 头像上传前的验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG 或 PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};

// 头像上传成功回调
const handleAvatarSuccess = (response) => {
  if (response.code === '200' && response.data) {
    registerForm.avatar = response.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error('头像上传失败，请重试');
  }
};

// 注册处理
const handleRegister = async (formEl) => {
  if (!formEl) return;
  
  await formEl.validate(async (valid) => {
    if (valid) {
      isSubmitting.value = true;
      const loading = ElLoading.service({
        lock: true,
        text: '注册中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      
      try {
        // 构建注册数据
        const registerData = {
          username: registerForm.username,
          password: md5(registerForm.password),
          nickname: registerForm.nickname || '',
          phone: registerForm.phone || '',
          email: registerForm.email || '',
          address: registerForm.address || '',
          avatarUrl: registerForm.avatar || '',
          role: 'user'  // 默认为普通用户
        };
        
        // 发送注册请求
        const response = await $axios.post('/register', registerData);
        
        if (response.code === '200') {
          ElMessage.success('注册成功，请登录');
          setTimeout(() => {
            router.push('/login');
          }, 1000);
        } else {
          ElMessage.error(response.msg || '注册失败，请稍后再试');
        }
      } catch (error) {
        console.error('注册出错:', error);
        ElMessage.error('注册失败，请稍后再试');
      } finally {
        loading.close();
        isSubmitting.value = false;
      }
    } else {
      ElMessage.warning('请正确填写注册信息');
    }
  });
};
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100%;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 40px 20px;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  overflow-y: auto;
}

.register-box {
  width: 680px;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  margin: 20px 0;
}

.register-header {
  padding: 30px 20px;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.register-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.register-header p {
  margin-top: 10px;
  font-size: 14px;
  opacity: 0.8;
}

.register-form {
  padding: 30px;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 0;
}

.form-item {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.avatar-upload {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-preview {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-icon {
  font-size: 30px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar-text {
  font-size: 12px;
  color: #666;
  margin-top: 8px;
}

.register-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  border-radius: 4px;
  margin-top: 10px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

.login-link a {
  color: #409EFF;
  text-decoration: none;
  margin-left: 5px;
}

.login-link a:hover {
  text-decoration: underline;
}

.register-footer {
  text-align: center;
  padding: 15px;
  font-size: 12px;
  color: #909399;
  border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .register-box {
    width: 100%;
  }
  
  .form-row {
    flex-direction: column;
    gap: 0;
  }
  
  .form-item {
    width: 100%;
  }
}
</style> 